package com.cngphone.AnFetion.Fetion.SIPC;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.cngphone.AnFetion.FetionFriend;
import com.cngphone.AnFetion.FetionMessage;
import com.cngphone.AnFetion.FetionSIPC;
import com.cngphone.AnFetion.FetionService;
import com.cngphone.AnFetion.FetionUri;
import com.cngphone.AnFetion.FriendManager;
import com.cngphone.AnFetion.HandleContactRequest;
import com.cngphone.AnFetion.MessageXml;
import com.cngphone.AnFetion.MiscUtil;
import com.cngphone.AnFetion.SendSMSActivity;
import com.cngphone.AnFetion.Settings;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive.IPackageReceivedHandler;
import com.cngphone.AnFetion.tools.LogUtil;
import com.cngphone.AnFetion.tools.StrUtil;
import com.cngphone.AnFetion2.R;

public class RemotePackageHandler extends SIPCBase implements IPackageReceivedHandler {
    private static final String TAG = "RemotePackageHandler";
    public int FETION_NOTIFYCATION_ID = Settings.FRIEND_NOTIFYCATION_ID + 1;
    private FetionService context;
    private FetionUri fetionid;
    private ArrayList<FetionFriend> buddies = null;

    private ArrayList<FetionFriend> getBuddies() {
        if (buddies == null) {
            buddies = context.getFriendManager().getBuddies();
        }
        return buddies;
    }

    // private message = new FetionMessage();

    public RemotePackageHandler(Context context, FetionUri fetionid, TcpSendAndReceive connection,
            SerialManager serialManager) {
        super(serialManager, connection);
        this.context = (FetionService) context;
        this.fetionid = fetionid;
    }

    @Override
    public boolean execute() {

        return false;
    }

    @Override
    public boolean received(FetionSIPC sipc) {
        try {
            if (sipc.isResponse()) return false;
            String cmd = sipc.getRequestCmdLine().cmd;
            if (cmd.equals("M")) {// 收到短消息
                // message.from
                String from = sipc.GetHeaderValue("F");

                FetionFriend fetionFriend = context.getFriendManager().getFriend(from);

                if (fetionFriend == null) {
                    context.setLastError("Receive message whose sender is not in buddies' list:" + from);
                    return false;
                }

                // ((FetionService)context).setLastError(sipc.body); //Tiger. Debug

                // 去掉字体信息
                Pattern pattern = Pattern.compile("<Font(.*?)>(.*?)</Font>");
                Matcher matcher = pattern.matcher(sipc.body);
                if (matcher.find()) sipc.body = matcher.group(2);
                sipc.body = StrUtil.xmlToString(sipc.body);

                from = fetionFriend.getName();
                String msg = from + " : " + sipc.body;
                fetionFriend.addMessage(new FetionMessage(fetionFriend,sipc.body, null));

                // bangbang.song@gmail.com
                // delegate to Service to do it.
                // FIXME: a temple solution.
                context.saveMessage(StrUtil.getPeopleId(fetionFriend.Uri), StrUtil.getPeopleId(context
                        .getMyself().Uri), sipc.body);

                SendSMSActivity chatActivity = FetionService.chatActivity;

                if (chatActivity != null && chatActivity.getFetionFriend() == fetionFriend) {
                    chatActivity.onReceiveMessage();
                } else {
                    fetionFriend.lastMessage = sipc.body;
                    if (Settings.DEBUG) LogUtil.d(TAG, msg);
                	FriendManager friendManager = context.getFriendManager();
                	friendManager.newMessageNotify(fetionFriend);
                    MiscUtil.notifyReceival(context);
                }

                ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();

                headers.add(new FetionSIPC.HeaderPair("F", sipc.GetHeaderValue("F")));
                headers.add(new FetionSIPC.HeaderPair("I", sipc.GetHeaderValue("I")));
                headers.add(new FetionSIPC.HeaderPair("Q", sipc.GetHeaderValue("Q")));
                headers.add(new FetionSIPC.HeaderPair("L", String.valueOf(0)));
                FetionSIPC res = new FetionSIPC("SIP-C/2.0 200 OK", headers, "");
                connection.SendSIPC(res);
                return true;
            } else if (cmd.equals("BN")) {// 收到通知
                if (sipc.GetHeaderValue("N").equals("contact")) {
                    // 加好友申请
                    MessageXml.AddBuddyApplicationMessage cm = new MessageXml.AddBuddyApplicationMessage();
                    if (cm.parseXml(sipc.body)) {
                        String msg = "我是" + cm.desc + ", 正在用中国移动飞信业务, 想加您为好友";
                        Notification info = new Notification(R.drawable.fetion, msg, System
                                .currentTimeMillis());
                        info.defaults = Notification.DEFAULT_ALL;
                        Intent contentIntent = new Intent(context, HandleContactRequest.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("contact", cm);
                        bundle.putString("sipc", sipc.toString());
                        bundle.putString("message", msg);
                        bundle.putInt("notify_id", FETION_NOTIFYCATION_ID);
                        contentIntent.putExtras(bundle);
                        PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent, 0);
                        info.setLatestEventInfo(context, "好友申请，点击批准", msg, appIntent);
                        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
                                .notify(FETION_NOTIFYCATION_ID++, info);
                        return true;
                    }

                    // 好友信息更新
                    MessageXml.UpdateBuddyMessage ubm = new MessageXml.UpdateBuddyMessage(getBuddies());
                    if (ubm.parseXml(sipc.body)) {
                        MiscUtil.notifyFriendChange(context);
                        return true;
                    }
                    
                    // 好友信息更新
                    MessageXml.ServiceResultMessage srm = new MessageXml.ServiceResultMessage(getBuddies());
                    if (srm.parseXml(sipc.body)) {
                        MiscUtil.notifyFriendChange(context);
                        for (FetionFriend friend : getBuddies()) {
							if (friend.getContactName() == null) {
								friend.setContactName(context.getContactName(friend.mobile_no));
							}
						}
                        return true;
                    }

                    LogUtil.w(TAG, "Contact unparsed! :" + sipc.body);
                } else if (sipc.GetHeaderValue("N").equals("permission")) {
                    Pattern pattern = Pattern.compile("<event type=\"BuddyPermissionChanged\">"
                            + "<permissions version=\"(.*)\"><permission "
                            + "uri=\"(.*?)\" values=\"identity=1;\"/></permissions></event>");
                    Matcher matcher = pattern.matcher(sipc.body);
                    if (matcher.find()) {
                        String uri = matcher.group(2);
                        FetionFriend fetionFriend = context.getFriendManager().getFriend(uri);
                        if (fetionFriend == null) {
                            fetionFriend = new FetionFriend();
                            fetionFriend.Uri = uri;
                            //fetionFriend.FriendName = null;
                            this.buddies.add(fetionFriend);
                            fetionFriend.type = Settings.TYPE_FRIEND;
                            MiscUtil.notifyFriendChange(context);
                            return true;
                        } else {
                            fetionFriend.type = Settings.TYPE_FRIEND;
                            MiscUtil.notifyFriendChange(context);
                            return true;
                        }
                    }
                }

            } else if (cmd.equals("I")) { // 会话邀请

                ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();
                headers.add(new FetionSIPC.HeaderPair("I", sipc.GetHeaderValue("I")));
                headers.add(new FetionSIPC.HeaderPair("Q", sipc.GetHeaderValue("Q")));
                headers.add(new FetionSIPC.HeaderPair("F", sipc.GetHeaderValue("F")));
                headers.add(new FetionSIPC.HeaderPair("K", "text/plain"));

                String body = "v=0\r\no=-0 0 IN " + this.connection.getLocalAddress() + ":"
                        + String.valueOf(this.connection.getLocalPort()) + "\r\ns=session\r\nc=IN IP4 "
                        + this.connection.getLocalAddress() + ":"
                        + String.valueOf(this.connection.getLocalPort())
                        + "\r\nt=0 0\r\nm=message 11181 sip " + this.fetionid.toString();
                headers.add(new FetionSIPC.HeaderPair("L", StrUtil.getLength(body)));
                FetionSIPC res = new FetionSIPC("SIP-C/2.0 200 OK", headers, body);
                connection.SendSIPC(res);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
